﻿using UnityEngine;
using System.Collections.Generic;
using LitJson;

/// <summary>
/// 本地玩家输入
/// </summary>
public class LocalController : MonoBehaviour {

    private Transform cameraTrs;
    private Player localPlayer;
    //保存上次的操作向量
    private Vector2 lastDirect = Vector2.zero;

    private void Start()
    {
        //获取主相机，并设置到主角身上
        cameraTrs = Camera.main.transform;
        cameraTrs.SetParent(transform);
        cameraTrs.localPosition = new Vector3(0, 6, -6);
        cameraTrs.localEulerAngles = new Vector3(30, 0, 0);

        //获取主角的Player脚本
        localPlayer = this.GetComponent<Player>();
    }

    void FixedUpdate()
    {
        if(localPlayer)
        {
            float dx = Input.GetAxisRaw("Horizontal");
            float dy = Input.GetAxisRaw("Vertical");

            Vector2 direct = new Vector2(dx, dy);

            if (lastDirect != direct)
            {
                lastDirect = direct;

                MoveData data = new MoveData();
                data.username = localPlayer.userData.username;
                data.direct = direct;
                data.position = localPlayer.transform.position;
                data.rotation = localPlayer.transform.eulerAngles;

                string json = JsonUtility.ToJson(data);
                NetworkManager.Instance.SendMessage(Protocol.PlayerMove_CMD, json);
            }

            localPlayer.Move(direct);
        }

    }

    float elapse = 0;
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            elapse = 0;
        }
        if (Input.GetKey(KeyCode.Space))
        {
            elapse += Time.deltaTime;

            localPlayer.SetArrowLegth(elapse*10);
        }
        if(Input.GetKeyUp(KeyCode.Space))
        {
            if(elapse > 0.5f)
            {
                float force = elapse * 10;

                //本机
                localPlayer.Fire(force, true);

                //网络
                FireData data = new FireData();
                data.username = localPlayer.userData.username;
                data.force = force;
                NetworkManager.Instance.SendMessage(Protocol.PlayerFire_CMD,JsonUtility.ToJson(data));
            }

            elapse = 0;
            localPlayer.SetArrowLegth(0);
        }
    }
}
